package cn.meetingroom.controller;

import cn.meetingroom.model.Room;
import cn.meetingroom.service.CheckCode;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javafx.scene.image.Image;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/UtilServlet/*")
public class UtilServlet extends BaseServlet {
    CheckCode image = new CheckCode();

    public void getRoomImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url = request.getParameter("url");
        String type = url.substring(url.lastIndexOf("."));
        Image image = new Image(url);
        ImageIO.write((RenderedImage) image,type,response.getOutputStream());
    }

    public void uploadRoomImg(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        SmartUpload smartUpload = new SmartUpload();
        Room room= new Room();
        ServletConfig config = this.getServletConfig();
        String imgUrl = "";
        smartUpload.initialize(config,request,response);
        try {
            smartUpload.upload();
            File smartFile = smartUpload.getFiles().getFile(0);
            String fileName = smartFile.getFilePathName();

            String type = fileName.substring(fileName.lastIndexOf("."));
            imgUrl =  UUID.randomUUID().toString()+type;
            smartFile.saveAs("D:\\Java\\IntelliJ IDEA Project\\MeetingRoom\\MeetingRoomImg\\"+imgUrl, SmartUpload.SAVE_PHYSICAL);
        } catch (SmartUploadException e){
            e.printStackTrace();
        }
        request.getSession().setAttribute("rImg","/MeetingRoomImg/"+imgUrl);
        response.getWriter().write("上传成功!!!");
    }

    public void checkImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageIO.write(image.getImage(),"JPEG",response.getOutputStream());
    }

    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter().print(image.getCode().equals(request.getParameter("checkCode")));

    }
}
